<template>
  <div class="page" >
    <el-row style="margin: -60px 0px 50px 0px;">
      <el-breadcrumb separator-class="el-icon-arrow-right">
        <el-breadcrumb-item :to="{ path: '/bashbord' }">首页</el-breadcrumb-item>
        <el-breadcrumb-item>主机管理</el-breadcrumb-item>
      </el-breadcrumb>
    </el-row>
    <div style="margin-bottom:20px">
      <el-row>
        <el-col :span="10">
          <el-button style="width:118px;margin-left:20px" type="primary" @click="addEcsShowDia" icon="el-icon-plus">添加主机</el-button>
          <el-select style="width:118px;margin-left:20px" clearable v-model="value" placeholder="请选择" @change="operation">
            <el-option
              v-for="item in options"
              :key="item.value"
              :label="item.label"
              :value="item.value">
            </el-option>
          </el-select>
        </el-col>
        <el-col :span="13" class="ecs_col">
          <el-row>
            <el-col :span="10" style="margin:0 10px 0 -10px">
              <el-input  maxlength="20" v-model="queryObj.name" clearable placeholder="请输入主机名称"></el-input>
            </el-col>
            <el-col :span="7">
              <el-button type="primary" @click="queryEcs(queryObj)">搜索</el-button>
            </el-col>
            <el-col :span="7">
              <el-button type="primary" @click="searchVisible =!searchVisible">高级搜索<i :class="[!searchVisible?adv_sty_hide : adv_sty_show]" /></el-button>
            </el-col>
          </el-row>
        </el-col>
      </el-row>
    </div>
    <advQuery :searchVisible="!searchVisible" :runStates="runStates" @advQuery="queryEcs" :inputHolder="inputHolder"></advQuery>
    <div v-loading="loading">
      <el-row>
        <el-table @selection-change="handleSelectionChange" :data="data.records" style="width: 100%;border-top: 1px solid #EBEEF5" :row-class-name="tableRowClassName" :header-cell-style="{'background':'#FAFAFA','text-align':'left'}">
          <el-table-column align="center" type="selection" prop="id" width="55"></el-table-column>
          <el-table-column align="left" prop="name" sortable label="主机名称" width="200">
            <template slot-scope="scope">
              <router-link style="text-decoration: none;color: #409EFF;" :to="queryDetail(scope.row.id)">{{scope.row.name}}</router-link>
            </template>
          </el-table-column>
          <el-table-column align="left" prop="ip" label="管理IP" sortable width="200"></el-table-column>
          <el-table-column align="left" prop="serviceIp" label="业务IP" sortable width="200"></el-table-column>
          <el-table-column align="left" prop="state" sortable label="运行状态" width="200">
            <template slot-scope="scope">
              <div v-if="scope.row.state == 'ACTIVE'">
                <div style="width: 8px;height: 8px;background-color: #409EFF;border-radius: 50%;display:inline-block"></div>
                <div style="display:inline-block">运行中</div>
              </div>
              <div v-if="scope.row.state == 'DISCONNECTION'">
                <div style="width: 8px;height: 8px;background-color: red;border-radius: 50%;display:inline-block"></div>
                <div style="display:inline-block">关闭</div>
              </div>
            </template>
          </el-table-column>
          <el-table-column align="left"  prop="memory"  sortable  label="内存" width="200">
            <template slot-scope="scope">
              <el-row>
                <el-col :span="20" style="display:flex;flex-direction:row;align-items:center;">
                  <el-progress :percentage="parseFloat(scope.row.memoryUsage>100?100:scope.row.memoryUsage)" :show-text="false" :stroke-width="10" style="width: 60px;" color="#60DD88"></el-progress>
                  <span style="margin-left:5px;">{{scope.row.memory}}</span>
                </el-col>
              </el-row>
            </template>
          </el-table-column>
          <el-table-column align="left"  prop="cpu" sortable label="CPU" width="200">
            <template slot-scope="scope" class="test">
              <el-row>
                <el-col style="display:flex;flex-direction:row;align-items:center;">
                  <el-progress :show-text="false" :percentage="parseFloat(scope.row.cpu>100?100:scope.row.cpu)" :stroke-width="10" color="#60DD88" style="width:60px"></el-progress>
                  <span style="margin-left:5px;">
                    {{scope.row.cpu+"%"}}
                  </span>
                </el-col>
              </el-row>
            </template>
          </el-table-column>
          <el-table-column align="left"  prop="diskCapacity" sortable label="磁盘容量" width="400">
            <template slot-scope="scope">
              <el-row>
                <el-col :span="20" style="display:flex;flex-direction:row;align-items:center;">
                  <el-progress :show-text="false" :percentage="parseFloat(scope.row.diskOccupancy>100?100:scope.row.diskOccupancy)" :stroke-width="10" color="#60DD88" style="width:60px;"></el-progress>
                  <span style="margin-left:5px;">
                    {{scope.row.diskCapacity}}
                  </span>
                </el-col>
              </el-row>
            </template>
          </el-table-column>
        </el-table>
      </el-row>
      <el-row>
        <el-col :span="12" :offset="12">
          <el-pagination
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
            :current-page="data.pageNo"
            :page-sizes="[10, 20, 30, 40]"
            :page-size="data.pageSize"
            layout="total, sizes, prev, pager, next, jumper"
            :total="data.total">
          </el-pagination>
        </el-col>
      </el-row>
    </div>

    <div>
      <el-dialog title="添加主机" :close-on-click-modal="false" :visible.sync="centerDialogVisible" top="292px" width="820px" @closed="addEcsClose">
        <el-form  v-loading="openLoading" :model="addEcsObj" status-icon  ref="addEcsObj" label-width="100px" class="addEcsForm" :rules="rules">
          <el-form-item>
            <el-row>
              <el-col :span="4" style="margin-left: -71px">查找主机:</el-col>
              <el-col :span="20"><span class="queryhost_title">您可以通过安装工具，提前规划配置，使用扩容工具进行快速扩容</span></el-col>
            </el-row>
            <el-row>
              <el-col :span="5">
                <el-upload
                  :show-file-list="false"
                  name="file"
                  class="upload-demo"
                  ref="upload"
                  :headers="{authorization:token}"
                  :action="uploadUrl"
                  :on-remove="uploadRemove"
                  :file-list="fileList"
                  :before-upload="beforeUpload"
                  :on-success="uploadSuccess"
                  :on-error="uploadError">
                  <el-button size="mini" type="primary" v-loading="uploading">模板添加主机</el-button>
                </el-upload>
              </el-col>
              <el-col :span="5">
                <a href="static/添加主机模板.xls" style="color: #409EFF;text-decoration: none;font-size: 14px">下载Excel模板</a>
              </el-col>
            </el-row>
          </el-form-item>
          <el-form-item label="主机名:" prop="name">
            <el-input maxlength="20" v-model="addEcsObj.name"></el-input>
            <el-tooltip placement="right">
              <div slot="content" style="width:300px;">输入的是要添加的主机的名称，字母大小写，字符，数字皆可</div>
              <i class="el-icon-question"></i>
            </el-tooltip>
          </el-form-item>
          <el-form-item label="账ㅤ号:" prop="userName">
            <el-input maxlength="20" v-model="addEcsObj.userName"></el-input>
            <el-tooltip placement="right">
              <div slot="content" style="width:300px;">输入的是要添加主机的账号，字母大小写，字符，数字皆可</div>
              <i class="el-icon-question"></i>
            </el-tooltip>
          </el-form-item>
          <el-form-item label="密ㅤ码:" prop="passWord">
            <el-input maxlength="20" type="password" v-model="addEcsObj.passWord"></el-input>
            <el-tooltip placement="right">
              <div slot="content" style="width:300px;">输入的是要添加的主机的密码，字母大小写，字符，数字皆可</div>
              <i class="el-icon-question"></i>
            </el-tooltip>
          </el-form-item>
          <el-form-item label="端ㅤ口:" prop="port">
            <el-input maxlength="5" v-model.number="addEcsObj.port"></el-input>
            <el-tooltip placement="right">
              <div slot="content" style="width:300px;">输入的是要添加的主机的通讯端口(shell)，只需输入端口号即可</div>
              <i class="el-icon-question"></i>
            </el-tooltip>
          </el-form-item>
          <el-form-item label="管理IP:" prop="ip">
            <el-input maxlength="20" v-model="addEcsObj.ip"></el-input>
            <el-tooltip placement="right">
              <div slot="content" style="width:300px;">输入的是要添加的主机的管理IP地址，即当前登录的设备的IP，只需输入IP地址即可，无需输入端口号</div>
              <i class="el-icon-question"></i>
            </el-tooltip>
          </el-form-item>
          <el-form-item label="业务IP:" prop="serviceIp">
            <el-input maxlength="20" v-model="addEcsObj.serviceIp"></el-input>
            <el-tooltip placement="right">
              <div slot="content" style="width:300px;">输入的是要当前登录账号的的通讯IP，只需输入IP地址即可，无需输入端口号</div>
              <i class="el-icon-question"></i>
            </el-tooltip>
          </el-form-item>

          <el-form-item style="margin-left: 250px">
            <el-button type="primary" @click="open">查找</el-button>
          </el-form-item>

          <el-form-item style="margin-top:68px;margin-left: -30px;" v-show="query">
            <h3 class="quer_res">查找结果:</h3>
            <div style="display:flex;justify-content: flex-end;width:100%">
              <div class="quer_res2" style="width:100%">
                连接{{hostItemTableData.filter(item=>item.state =='ACTIVE').length}}台,未连接{{hostItemTableData.filter(item=>item.state !='ACTIVE').length}}台
              </div>
              <el-input placeholder="请输入管理IP" @input="filterHandler" clearable icon="el-icon-search" v-model.trim="hostIp_query" style="width:163px;height:40px;margin:-30px 0 10px 0"></el-input>
            </div>
            <el-table height="350px" :header-cell-style="{background:'#FAFAFA'}" :data="hostItemTableData"  @selection-change="selChange" style="width: 100%;">
              <el-table-column :selectable="filterSelect" type="selection" width="55"></el-table-column>
              <el-table-column align="center" prop="name" disabled label="主机名称" width="180"></el-table-column>
              <el-table-column align="center" prop="ip" label="管理IP" width="180"></el-table-column>
               <el-table-column align="center" prop="serviceIp" label="业务IP" width="180"></el-table-column>
              <el-table-column align="center" prop="state" label="状态" width="100" :formatter="parseState">
               <template slot-scope="scope">
                  <div v-if="scope.row.state == 'ACTIVE'">
                    <img src="../../assets/img/xuanzhong.png">
                    <div style="display:inline-block;">运行中</div>
                  </div>
                  <div v-else>
                    <img src="../../assets/img/xingzhuang.png">
                    <div style="display:inline-block">关闭</div>
                  </div>
                </template>
              </el-table-column>
            </el-table>
            <div style="margin:20px 0 0 220px">
              <el-button  @click="addEcsHideDia">取消</el-button>
              <el-button type="primary" @click="addEcsSave('addEcsObj',addEcsObj)">确认</el-button>
            </div>
          </el-form-item>


        </el-form>
      </el-dialog>
    </div>
    <div>
      <el-dialog :visible.sync="dialogVisible" v-model="dialogVisible" title="提示" width="540px" @closed="closeDelDia" v-loading="loading2">
        <span>删除主机会一并卸载实例,确认删除此主机?</span>
        <template #footer>
          <div class="adv_del">
            <el-button @click="dialogVisible = false">取消</el-button>
            <el-button type="primary" v-loading="loading" @click="delEcs">确认</el-button>
          </div>
        </template>
      </el-dialog>
    </div>
  </div>
</template>


<script>
import '../../../config/index'
import '../../assets/iconfont/iconfont.css';
import {doGet, doPost} from '@/api/index.js'
import '../../css/style.css';
import advQuery from '../../components/advQuery/advQuery.vue';
  export default {
    components:{
      advQuery
    },
    data () {
      return {
        loading2:'',
        openLoading:false,
        hostIp_query:'',
        loading:false,
        file:'',
        multipleSelection:[],
        hostItemTableData:[],
        hostItemTableData_copy:[],
        token:'',
        uploadUrl:`${process.env.UPLOAD_PARAM}/sys_ecs/analysisExcel`,
        fileList:[],
        innerVisible:false,
        inputHolder:["请输入管理ip","请输入业务ip","请选择运行状态"],
        adv_sty_show:"iconfont icon-xiangxiazhanhang",
        adv_sty_hide:"iconfont icon-xiangshangzhanhang",
        searchVisible:true,
        centerDialogVisible:false,
        dialogVisible:false,
        options: [{
          value: 'del',
          label: '删除'
        }],
        runStates: [{
          value: 'ACTIVE',
          label: '运行中'
        },{
          value: 'SHUTTING_DOWN',
          label: '关闭'
        }],
        value: '',

        data: {
          total: 0,
          pageNo: 1,
          pageSize:10,
          records:[]
        },
        rules: {
                name:[{required: true, message:'请输入主机名', trigger: 'blur'}],
                userName: [{required: true, message:'请输入账号', trigger: 'blur'}],
                passWord: [{required: true, message:'请输入密码', trigger: 'blur'}],
                port:[{type:'number',message:'请输入数字',trigger:'blur'}],
                ip:[{required: true,message:'请输入管理IP',trigger:'blur'}],
                serviceIp:[{required: true,message:'请输入业务IP',trigger:'blur'}],
        },
        addEcsObj:{
          "name":'',
          "ip":'',
          "serviceIp":"",
          "port":22,
          "userName":'',
          "passWord":'',
          "state":'',
          // "clustersNum":'',
          // "runNum":'',
          // "closeNum":'',
          // "memory":'',
          // "cpu":"",
          // "query":""
        },
        queryObj:{
          ip:'',
          name:'',
          serviceIp:'',
          runState:'',
          pageNo:'',
          pageSize:''
        },
        ecsIds:[],
        addDataList:[],
        query:false,
        queryBtn:true,
        clock:null,
        flag:true,
        uploading:false
      }
    },
    mounted(){
      this.queryEcs({});
      this.loading=true;
      this.clock=setInterval(()=>{
        if(this.flag){
          this.queryEcsInterval({})
        }
      },1000);
      this.token=JSON.parse(localStorage.getItem('userInfo')).authorization;
    },
    beforeDestroy()
    {
      clearInterval(this.clock)
      this.clock=null;
    },
    methods: {
      beforeUpload(file){
        this.uploading=true;
        let split = file.name.split(".");
        let fileName = split[split.length-1];
        const fileTypeLim = fileName === 'xls' || fileName === 'xlsx' ;
        const fileSizeLim = file.size / 1024 / 1024 < 5;
        if (!fileTypeLim) {
          this.$message.error('只能上传 xls或xlsx 格式文件!');
          this.uploading=false;
          return
        }
        if (!fileSizeLim) {
          this.$message.error('上传文件大小不能超过 5MB!');
          this.uploading=false;
          return
        }
        this.loadVis=true;
        return fileTypeLim && fileSizeLim;
      },
      open() {
        if (this.addEcsObj.name == '' && this.addEcsObj.ip == '' && this.addEcsObj.serviceIp == '' && this.addEcsObj.userName == '' && this.addEcsObj.passWord == ''  && this.hostItemTableData.length == 0)
        {
          this.$message.error('请至少填写或导入一个主机')
        }
        else
        {
          this.openLoading=true;
          if (this.addEcsObj.name !== '' && this.addEcsObj.ip !== '' && this.addEcsObj.serviceIp !== '' && this.addEcsObj.userName !== '' && this.addEcsObj.passWord !== '' && this.addEcsObj.port !== '')
          {
            let length = this.hostItemTableData.filter(i => i.ip == this.addEcsObj.ip).length
            if (length == 0)
            {
              this.hostItemTableData.push(this.addEcsObj);
            }
            else
            {
              for(let i=0;i<this.hostItemTableData.length;i++)
              {
                if(this.hostItemTableData[i].ip==this.addEcsObj.ip)
                {
                  this.hostItemTableData[i]=this.addEcsObj;
                }
              }
            }
          }
          this.checkHost()
        }
      },
      filterHandler(){
        if (this.hostIp_query==""){
          this.hostItemTableData=this.hostItemTableData_copy;
        }else {
          this.hostItemTableData_copy=this.hostItemTableData;
          this.hostItemTableData =this.hostItemTableData.filter(item=>item.ip.indexOf(this.hostIp_query) != -1)
        }
      },
      filterSelect(row,index){
        if(row.state =='ACTIVE'){
          return true;
        }
        return false;
      },
      httpRequest(param) {
       this.file = param.file
      },
      uploadRemove(){
        this.fileList=[];
      },
      uploadError(err){

   if(row.state =='ACTIVE'){
          return true;
        }
        return false;
      },
      httpRequest(param) {
       this.file = param.file
      },
      uploadRemove(){
        this.fileList=[];
      },
      uploadError(err){

        this.fileList=[];
      },
      uploadSuccess(data) {
        if(data.code==0)
        {
          this.$message.success(data.msg);
          for(let i=0;i<data.data.length;i++)
          {
            this.hostItemTableData.push(data.data[i]);
          }
          this.uploading=false
        }
        else
        {
          this.uploading=false;
          this.$message.error("上传的文件内容有误，请检查")
        }
      },
      checkHost(){
        let url="/sys_ecs/checkHost";
        doPost(url,this.hostItemTableData).then(res=>{
          if(res.data.code===0){
            this.hostItemTableData=res.data.data;
            this.query = true
            this.openLoading=false;
          }
        });
      },

      queryDetail(id){
        return {path:'/ecs-detail',query:{hostId:id}};
      },
      closeDelDia(){
        this.value='';
      },
      handleSelectionChange(val){
        this.ecsIds=[];
        val.forEach(item => {
          this.ecsIds.push(item.id)
        });
      },
      selChange(val){
        this.addDataList=val;
      },
      operation(e){
        if(this.ecsIds.length==0){
          this.value='';
          return this.$message.error("请先选择需要删除的主机!");
        }else {
          this.dialogVisible=true;
          this.value=this.options[0].value;
        }
      },
      delEcs(){
        this.loading2 = true;
        let url="/sys_ecs/delete";
        doPost(url,this.ecsIds).then(res=>{
          this.dialogVisible=false;
          this.loading2 = false;
          if(res.data.code===0){
            this.$message.success(res.data.msg);
            this.value='';
            this.queryEcs({});
          }
        });
      },
      parseState(row,column){
        return this.runStates.filter(item=>item.value == row.state)[0].label;
      },
      addEcsShowDia(){
        this.queryBtn=true;
        this.query=false,
        this.addEcsObj={
          "name":'',
          "ip":'',
          "serviceIp":"",
          "port":22,
          "userName":'',
          "passWord":'',
          "state":''
        },
        this.hostItemTableData_copy=[],
        this.hostItemTableData=[],
        this.file='',
        this.fileList=[],
        this.centerDialogVisible=true;
      },
      addEcsHideDia(){
        this.centerDialogVisible=false;
      },
      addEcsSave(obj){
        let url="/sys_ecs/add";
        if (this.addDataList.length == 0){
          this.$message.error("请至少选择一个主机");
        }else {
          doPost(url,this.addDataList).then(res=>{
            if (res.data.code === 0){
              if (JSON.stringify(res.data.data) === '{}'){
                this.$message.success(res.data.msg);
              }else {
                this.$alert(JSON.stringify(res.data.data), '提示', {
                  confirmButtonText: '确定',
                });
              }
              this.queryEcs({});
            }else {
              this.$message.success(res.data.msg);
            }
          });
          this.addEcsHideDia();
        }
      },
      addEcsClose(){
        this.clearAddDia();
      },
      clearAddDia(){
        this.addEcsObj={};
        this.addEcsObj.port=22;
      },
      queryEcs(obj){
        let that=this;
        that.loading=true;
        let url="/sys_ecs/page";
        obj.pageNo=this.data.pageNo;
        obj.pageSize=this.data.pageSize;
        doGet(url,obj).then(res=>
        {
          if(res.data.code===0)
          {
            that.data.records=res.data.data.records;
            // if(that.data.records.length==0)
            // {
            //   this.$router.push('/guide')
            // }
          }
          that.loading=false;
        });
      },
      queryEcsInterval(obj){
        if(this.data.records.length==0){return;}
        let that=this;
        that.flag = false;
        let url="/sys_ecs/page";
        obj.pageNo=this.data.pageNo;
        obj.pageSize=this.data.pageSize;
        doGet(url,obj).then(res=>
        {
          if(res.data.code===0)
          {
            let arr=res.data.data.records;
            for(let i=0;i<arr.length;i++)
            {
              for(let j=0;j<that.data.records.length;j++)
              {
                if(that.data.records[j].id==arr[i].id)
                {
                  that.data.records[j].state=arr[i].state;
                  that.data.records[j].memory=arr[i].memory;
                  that.data.records[j].cpu=arr[i].cpu;
                  that.data.records[j].diskCapacity=arr[i].diskCapacity;
                }
              }
            }
            that.data.total=res.data.data.total;
          }
          that.loading=false;
          setTimeout(()=>{
            that.flag = true;
          },5000)
        });
      },
      handleSizeChange (val) {
        this.data.pageSize=val;
        this.queryEcs({})
      },
      handleCurrentChange (val) {
        this.data.pageNo=val;
        this.queryEcs({})
      },
      tableRowClassName ({row, rowIndex}) {
        if (rowIndex === 1) {
          return 'warning-row'
        } else if (rowIndex === 3) {
          return 'success-row'
        }
        return ''
      }
    },
  }
</script>


<style scoped>
.hostSty{
  display: flex;
  margin: -5px 0px;
}
.quer_res2{
  width: 137px;
  height: 17px;
  font-size: 12px;
  font-family: PingFangSC-Regular, PingFang SC;
  font-weight: 400;
  color: #999999;
  line-height: 17px;
}
.quer_res{
  width: 80px;
  height: 22px;
  font-size: 16px;
  font-family: PingFangSC-Medium, PingFang SC;
  font-weight: 500;
  color: #333333;
  line-height: 22px;
  margin-top: -20px;
}
  .el-table .warning-row {
    background: oldlace;
  }

  .el-table .success-row {
    background: #f0f9eb;
  }
  .breadcrumbColor{
    color: #B9B9B9 !important;
  }
  .page{
    margin-left: 20px;
    margin-top:80px;
  }
.queryhost_title {
  width: 348px;
  height: 17px;
  font-size: 12px;
  font-family: PingFangSC-Regular, PingFang SC;
  font-weight: 400;
  color: #999999;
  line-height: 40px;
  margin-right: 81px;
}
</style>
